import ProductService from '../../services/product'
import { Utils } from '../../utils/utils'
import ProductUtils from '../../utils/product'
import { User as UserUtils } from '../../utils/user'
import {
    fastLoanTimeLimitOptions,
    allJobsOptions,
    yesOrNoOptions,
    hasOrNoOptions,
    houseTypeOptions,
    hasCarOptions,
    creditStatusOptions
  } from '../../config';

import Apply from '../../model/apply-form'

const productService = new ProductService()
const utils = new Utils()
const productUtils = new ProductUtils()
const userUtils = new UserUtils()
const defaultForm: Apply[] = [{
    label: '贷款额度',
    name: 'loan_limit',
    type: 'input',
    inputType: 'number',
    toThrousand: true,
    suffix: '元',
    placeholder: '请输入贷款额度',
    isRequire: true,
    numberRangeMin: 1000,       // 最小额度是1000
    numberRangeMax: 20000000,   // 最大额度是20000000
    numberRangeMinTips: '额度不能小于%s元',
    numberRangeMaxTips: '额度不能大于%s元',
  }, {
    label: '贷款期限',
    name: 'loan_date_limit',
    type: 'select',
    mode: 'selector',
    options: fastLoanTimeLimitOptions,
    rangeKey: 'name',
    optionValueKey: 'value',
    placeholder: '请选择',
    isRequire: true,
  }, {
    label: '职业身份',
    name: 'indentity',
    type: 'select',
    options: allJobsOptions,
    rangeKey: 'name',
    optionValueKey: 'value',
    placeholder: '请选择',
    isRequire: true,
  }, {
    label: '是否有本地公积金',
    name: 'local_accumulation',
    type: 'select',
    options: hasOrNoOptions,
    rangeKey: 'name',
    optionValueKey: 'value',
    placeholder: '请选择',
  }, {
    label: '是否有本地社保',
    name: 'had_social_security',
    type: 'select',
    options: hasOrNoOptions,
    rangeKey: 'name',
    optionValueKey: 'value',
    placeholder: '请选择',
  }, {
    label: '名下房产类型',
    name: 'house_type',
    type: 'select',
    options: houseTypeOptions,
    rangeKey: 'name',
    optionValueKey: 'value',
    placeholder: '请选择',
  }, {
    label: '名下是否有车',
    name: 'had_car',
    type: 'select',
    options: hasCarOptions,
    rangeKey: 'name',
    placeholder: '请选择',
  }, {
    label: '您的信用情况',
    name: 'credit',
    type: 'select',
    options: creditStatusOptions,
    rangeKey: 'name',
    optionValueKey: 'value',
    placeholder: '请选择',
  }, {
    label: '联系人姓名',
    name: 'name',
    type: 'input',
    placeholder: '请输入联系人姓名',
    isRequire: true,
  }, {
    label: '联系电话',
    name: 'tel',
    type: 'input',
    placeholder: '请填写联系电话',
    isRequire: true,
    validator: [userUtils.phoneNumberValidation]
  }, {
    label: '所在城市',
    name: 'city_code',
    type: 'select',
    mode: 'region',
    // options: utils.getInitRegionsById(),
    rangeKey: 'name',
    placeholder: '请选择',
    isRequire: true,
    regionRange: 2,
  }, {
    label: '年龄',
    name: 'age',
    type: 'select',
    options: productUtils.initAgeOptions(),
    toThrousand: true,
    suffix: '周岁',
    placeholder: '请选择您的年龄/周岁',
    isRequire: true,
  }, {
    label: '是否购买商业保险',
    name: 'had_insurance',
    type: 'select',
    mode: 'selector',
    options: yesOrNoOptions,
    rangeKey: 'name',
    optionValueKey: 'value',
    placeholder: '请选择',
  }, {
    label: '是否申请过无抵押贷款',
    name: 'had_mortgage',
    type: 'select',
    options: yesOrNoOptions,
    rangeKey: 'name',
    optionValueKey: 'value',
    placeholder: '请选择',
  }
]
// 表单默认值
const formValue = {
  loan_limit: 10000,
  loan_date_limit: 6,
  // indentity: '',
  // local_accumulation: '',
  // had_social_security: '',

}

/**
 * 根据产品对象初始化表单数据
 */
function initFrom (product: any): any {
  const form = {}
  form['loan_limit'] = product.min_deposit
  form['loan_date_limit'] = product.min_time_limit
  return form
}

/**
 * 根据产品更新表单的额度和期限规则
 */
function updateFormDepositRule(formRule: any[], product: any): any {
  const copyFormRule = [...formRule]
  
  copyFormRule.forEach(item => {
    const name = item.name

    if ('loan_limit' === name) {
      item.numberRangeMin = product.min_deposit
      item.numberRangeMax = product.max_deposit
      item.numberRangeMinTips = `产品最小额度是${productUtils.converToTenThousand(product.min_deposit)}万元`
      item.numberRangeMaxTips = `产品最大额度是${productUtils.converToTenThousand(product.max_deposit)}万元`
    } else if ('loan_date_limit' === name) {
      item.options = productUtils.getTimeLimitObjOptions(product)
    }
  })

  return copyFormRule
}

export default {
  namespace: 'fastProductApply',
  state: {
   product: {},   // 产品
   allTimeLimitOptions: [],  // 产品贷款期限数组
   form: defaultForm,
   formValue,
   isAgreeProtocol: false,  // 是否同意协议
   depositTimeEventSuffix: `_${utils.random(10)}`   // 贷款期限改变事件后缀
  },
  effects: {
    // 查询快速产品详情
    * getFastProductDetail({ payload }, {call, put, select}) {
      
      const { code, data } = yield call(productService.getFastDetail.bind(productService),  payload.product_id )
  
      if (code === 0) {
        
        // 计算产品的贷款期限数组
        const allTimeLimitOptions = productUtils.getTimeLimitOptions(data)

        // 计算产品的额度范围和贷款期限范围
        const formRules = updateFormDepositRule(defaultForm, data)

        // 初始化表单
        const form = initFrom(data)
        // 更新表单
        yield put({ type: 'updateFormItem', payload: {
          formItem: {
            name: 'loan_limit',
            value: form.loan_limit,
          }
        }})
        yield put({type: 'updateFormItem', payload: {
          formItem: {
            name: 'loan_date_limit',
            value: form.loan_date_limit,
          }
        }})

        // 更新model
        yield put({ type: 'save', payload: {
          product: data,
          allTimeLimitOptions,
          form: formRules,
        } });
      }
    },
  },
  reducers: {
    // 更新state
    save(state, { payload }) {
      return {...state, ...payload};
    },
    // 更新表单项
    updateFormItem(state, { payload }) {
      const { formValue } = state
      const { formItem } = payload
      
      const formCopy = Object.assign({}, formValue)
      formCopy[formItem.name] = formItem.value
      
      return {...state, formValue: formCopy }
    },
    // 更新表单
    updateForm(state, { payload }) {
      const { formValue } = state
      const newForm = payload
      
      const formCopy = Object.assign({}, formValue, newForm)
      return {...state, formValue: formCopy }
    }
  },
};
